# @Author   : tan90
# @Time     : 2025/1/25 08:58
import random
import signal
import sys

import paho.mqtt.client as mqtt
from loguru import logger
from pyrtcm import RTCMReader

# 连接信息
client_id = f"py_rtcm_{random.randint(1000, 9999)}"
port = 1883
clean_session = True
keepalive = 10

host = "180.107.109.102"
username = "admin"
password = "nttieren0513"

topic_list = [
    (f"device/+/upload", 1),
]


def initMqtt():
    def handler(topic: str, payload: bytes):
        logger.info(f"【{topic}】收到消息：{payload}")
        try:
            msg = RTCMReader.parse(payload)
            logger.info(msg)
        except Exception as e:
            logger.error(e)

    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            # 订阅主题
            logger.info(f"【{host} {port}】mqtt客户端连接成功")
            # 订阅主题
            client.subscribe(topic_list)

    def on_disconnect(client, userdata, rc):
        logger.info(f"【{host} {port}】mqtt客户端断开连接 {rc}")

    def on_subscribe(client, userdata, mid, granted_qos):
        print(f"【{host} {port}】mqtt客户端订阅成功 {mid} {granted_qos}")

    def on_message(client, userdata, msg):
        handler(msg.topic, msg.payload)

    mqtt_client = mqtt.Client(client_id=client_id, clean_session=clean_session)
    mqtt_client.username_pw_set(username, password)
    mqtt_client.on_connect = on_connect
    mqtt_client.on_subscribe = on_subscribe
    mqtt_client.on_message = on_message
    mqtt_client.on_disconnect = on_disconnect
    mqtt_client.connect(host, port, keepalive)

    def signal_handler(signum, frame):
        logger.info(f"正在关闭 MQTT 客户端...")
        mqtt_client.loop_stop()
        mqtt_client.disconnect()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    # 保持网络循环，等待消息
    mqtt_client.loop_forever()


def initLog(level: str):
    logger.remove()
    log_format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | " \
                 "<level>{level}</level> | " \
                 "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | " \
                 "<level>{message}</level>"
    logger.add(sys.stderr, format=log_format, level=level)


if __name__ == "__main__":
    initLog("INFO")
    initMqtt()
